package com.example.administrator.myproject.merchant

import android.Manifest
import android.annotation.TargetApi
import android.app.Activity
import android.content.ContentUris
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast


import java.io.BufferedOutputStream
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date

import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.SaveListener
import com.example.administrator.myproject.R
import com.example.administrator.myproject.R.*
import com.example.administrator.myproject.bean.BobmBean
import java.lang.Long

/**
 * 上架
 */
class Grounding : AppCompatActivity(), View.OnClickListener {
    private var mingcheng: EditText? = null
    private var leixing: EditText? = null
    private var jiage: EditText? = null
    private var kucun: EditText? = null
    private var shuoming: EditText? = null
    private var imageView: ImageView? = null
    private var popWnd: PopupWindow? = null
    private var imageUri: Uri? = null
    private var file: File? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(layout.grounding_view)
        mingcheng = findViewById(id.name_et)
        leixing = findViewById(id.type_et)
        jiage = findViewById(id.moeny_et)
        kucun = findViewById(id.kucun_et)
        imageView = findViewById(id.icon_iv)
        shuoming = findViewById(id.shuoming_et)
        findViewById<View>(id.add_icon).setOnClickListener(this)
        findViewById<View>(id.fabu_btn).setOnClickListener(this)
    }

    override fun onClick(view: View) {
        when (view.id) {
            id.add_icon -> {
                val contentView = LayoutInflater.from(this).inflate(layout.popup, null)
                val xiangce = contentView.findViewById<TextView>(id.xiangce)
                val xiangji = contentView.findViewById<TextView>(id.xiangji)
                val quxiao = contentView.findViewById<TextView>(id.quxiao)
                xiangce.setOnClickListener(this)
                xiangji.setOnClickListener(this)
                quxiao.setOnClickListener(this)
                popWnd = PopupWindow(this)
                popWnd!!.contentView = contentView
                popWnd!!.width = ViewGroup.LayoutParams.MATCH_PARENT
                popWnd!!.height = ViewGroup.LayoutParams.MATCH_PARENT
                popWnd!!.showAsDropDown(mingcheng, 0, 0)
            }
            id.xiangce -> {
                popWnd!!.dismiss()
                //动态申请获取访问 读写磁盘的权限
                if (ContextCompat.checkSelfPermission(this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 101)
                } else {
                    //打开相册
                    val intent = Intent(Intent.ACTION_GET_CONTENT)
                    //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
                    intent.type = "image/*"
                    startActivityForResult(intent, PICK_PHOTO) // 打开相册
                }
            }
            id.xiangji -> {
                popWnd!!.dismiss()
                // 创建File对象，用于存储拍照后的图片
                //存放在手机SD卡的应用关联缓存目录下
                val outputImage = File(externalCacheDir, "output_image.jpg")
                /* 从Android 6.0系统开始，读写SD卡被列为了危险权限，如果将图片存放在SD卡的任何其他目录，
                  都要进行运行时权限处理才行，而使用应用关联 目录则可以跳过这一步
                */
                try {
                    if (outputImage.exists()) {
                        outputImage.delete()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }

                /*
                   7.0系统开始，直接使用本地真实路径的Uri被认为是不安全的，会抛 出一个FileUriExposedException异常。
                   而FileProvider则是一种特殊的内容提供器，它使用了和内 容提供器类似的机制来对数据进行保护，
                   可以选择性地将封装过的Uri共享给外部，从而提高了 应用的安全性
                 */
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //大于等于版本24（7.0）的场合
                    imageUri = FileProvider.getUriForFile(this@Grounding, "com.feige.pickphoto.fileprovider", outputImage)
                } else {
                    //小于android 版本7.0（24）的场合
                    imageUri = Uri.fromFile(outputImage)
                }

                //启动相机程序
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                //MediaStore.ACTION_IMAGE_CAPTURE = android.media.action.IMAGE_CAPTURE
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
                startActivityForResult(intent, TAKE_CAMERA)
            }
            id.quxiao -> popWnd!!.dismiss()
            id.fabu_btn -> {
                val name = mingcheng!!.text.toString()
                val type = leixing!!.text.toString()
                val money = jiage!!.text.toString()
                val coum = kucun!!.text.toString()
                val jieshao = shuoming!!.text.toString()
                if (name.isEmpty() || type.isEmpty() || money.isEmpty() || coum.isEmpty() || jieshao.isEmpty()) {
                    Toast.makeText(this, "请填写商品信息", Toast.LENGTH_SHORT).show()
                } else {
                   // if (file == null) {
                    //    Toast.makeText(this, "请添加图片", Toast.LENGTH_SHORT).show()
                   //} else {
                        val bobmBean = BobmBean()
                        bobmBean.coum = coum
                        bobmBean.type = type
                        bobmBean.name = name
                        bobmBean.money = money.toInt()
                        bobmBean.explain = jieshao
                      //  bobmBean.file = file!!.toString()
                        bobmBean.save(object : SaveListener<String>() {
                            override fun done(s: String, e: BmobException?) {
                                if (e == null) {
                                    Toast.makeText(this@Grounding, "发布成功", Toast.LENGTH_SHORT).show()
                                    finish()
                                } else {
                                    Toast.makeText(this@Grounding, "发布失败", Toast.LENGTH_SHORT).show()
                                }
                            }
                        })
                  //  }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            TAKE_CAMERA -> if (resultCode == Activity.RESULT_OK) {
                try {
                    // 将拍摄的照片显示出来
                    val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri!!))
                    file = getFile(bitmap)
                    imageView!!.setImageBitmap(bitmap)
                } catch (e: FileNotFoundException) {
                    e.printStackTrace()
                }

            }
            PICK_PHOTO -> if (resultCode == Activity.RESULT_OK) { // 判断手机系统版本号
                if (Build.VERSION.SDK_INT >= 19) {
                    // 4.4及以上系统使用这个方法处理图片
                    handleImageOnKitKat(data!!)
                } else {
                    // 4.4以下系统使用这个方法处理图片
                    handleImageBeforeKitKat(data!!)
                }
            }
            else -> {
            }
        }
    }

    @TargetApi(19)
    private fun handleImageOnKitKat(data: Intent) {
        var imagePath: String? = null
        val uri = data.data
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            val docId = DocumentsContract.getDocumentId(uri)
            if ("com.android.providers.media.documents" == uri!!.authority) {
                val id = docId.split(":".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1]
                // 解析出数字格式的id
                val selection = MediaStore.Images.Media._ID + "=" + id
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
            } else if ("com.android.providers.downloads.documents" == uri.authority) {
                val contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId))
                imagePath = getImagePath(contentUri, null)
            }
        } else if ("content".equals(uri!!.scheme!!, ignoreCase = true)) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null)
        } else if ("file".equals(uri.scheme!!, ignoreCase = true)) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.path
        }
        // 根据图片路径显示图片
        displayImage(imagePath)
    }

    /**
     * android 4.4以前的处理方式
     *
     * @param data
     */
    private fun handleImageBeforeKitKat(data: Intent) {
        val uri = data.data
        val imagePath = getImagePath(uri, null)
        displayImage(imagePath)
    }

    private fun getImagePath(uri: Uri?, selection: String?): String? {
        var path: String? = null
        // 通过Uri和selection来获取真实的图片路径
        val cursor = contentResolver.query(uri!!, null, selection, null, null)
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
            }
            cursor.close()
        }
        return path
    }

    private fun displayImage(imagePath: String?) {
        if (imagePath != null) {
            val bitmap = BitmapFactory.decodeFile(imagePath)
            file = getFile(bitmap)
            imageView!!.setImageBitmap(bitmap)
        } else {
            Toast.makeText(this, "获取相册图片失败", Toast.LENGTH_SHORT).show()
        }
    }

    //把bitmap转成file
    fun getFile(bitmap: Bitmap): File {
        val formatter = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss")
        val curDate = Date(System.currentTimeMillis())
        val str = formatter.format(curDate)
        val file = File(filesDir, "$str.png")

        try {
            val bos = BufferedOutputStream(FileOutputStream(file))
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return file
    }

    companion object {
        private val TAG = "Grounding"
        val TAKE_CAMERA = 101
        val PICK_PHOTO = 102
    }
}
